package com.zhongli.devplatform.utils.excel;

import com.zhongli.devplatform.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

@Slf4j
public class ResponseUtil {

    public static void exportExcel(HttpServletResponse response, String fileName, Workbook workbook) {
        OutputStream os = null;
        try {
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName));
            os = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/vnd.ms-excel;charset=gb2312");
            //将excel写入到输出流中
            workbook.write(os);
        } catch (Exception e) {
            log.error(e.getLocalizedMessage());
            throw new ServiceException("导出excel文件失败");
        } finally {
            try {
                os.flush();
                os.close();
            } catch (Exception e) {
                log.error(e.getLocalizedMessage());
                throw new ServiceException("导出excel文件失败");
            }

        }

    }

}
